package com.lge.qcontact;

import java.net.MalformedURLException;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.lge.qcontact.members.FindAccountActivity;
import com.lge.qcontact.members.RegistMemberActivity;
import com.lge.qcontact.threads.SyncronizeContactsThread;
import com.lge.qcontact.utils.LocalDBHelper;
import com.lge.qcontact.utils.MUtils;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class MainActivity extends Activity {

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String uEmail;
	private String uPassword;
	private String uId;

	// UI references.
	private EditText uIdEdit;
	private EditText uPwEdit;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;

	// LocalDB
	private LocalDBHelper lDBHelper;
	private SQLiteDatabase localDB;


	private boolean is_login = false;// 로그인여부결정
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		
		lDBHelper = new LocalDBHelper(this);
		localDB = lDBHelper.getWritableDatabase();

		// Set up the login form.
		uIdEdit = (EditText) findViewById(R.id.id);

		uPwEdit = (EditText) findViewById(R.id.password);
		uPwEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView textView, int id,
					KeyEvent keyEvent) {
				if (id == R.id.login || id == EditorInfo.IME_NULL) {
					attemptLogin();
					return true;
				}
				return false;
			}
		});

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Cursor c = localDB.rawQuery("select uid from LOGIN_INFO;", null);
						if(c.getCount() > 0){
							c.moveToNext();
							if(c.getString(0).equals(uIdEdit.getText().toString())) attemptLogin();
							else{
								AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
								builder.setTitle("주의!");
								builder.setMessage("최초 접속과 다른 ID로 로그인 시 기존 연락처 데이터가 삭제됩니다.\n 로그인 하시겠습니까?");
								builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface arg0, int arg1) {
										localDB.execSQL("delete from LOGIN_INFO");
										localDB.execSQL("delete from CONTACTS");
										attemptLogin();
									}
								});
								builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										
									}
								});
								builder.show();
							}
						}else{
							attemptLogin();
						}
						
						c.close();
						
					}
				});

		findViewById(R.id.sign_in_button_local).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Cursor c = localDB.rawQuery("select * from LOGIN_INFO;", null);
						if(c.getCount() > 0){
							c.moveToNext();
							
							Intent regIntent = new Intent(MainActivity.this,
									GroupListActivity.class);
							regIntent.putExtra("uid", c.getString(0));
							startActivity(regIntent);
							finish();
						}else{
							MUtils.toast(getBaseContext(), "최초 1회 로그인이 필요합니다.");
						}
						
					}
				});

		findViewById(R.id.sign_in_button_registration).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Intent regIntent = new Intent(MainActivity.this,
								RegistMemberActivity.class);
						regIntent.putExtra("uid", uIdEdit.getText());
						startActivity(regIntent);
						
					}
				});
		
		
		Cursor c = localDB.rawQuery("select * from LOGIN_INFO;", null);
		MUtils.loge("cusor size = " + c.getCount());
		if(c.getCount() >0){
			c.moveToNext();
			if(c.getString(2) != null &&c.getString(2).equals("true")){
				uIdEdit.setText(c.getString(0));
				uPwEdit.setText(c.getString(1));
				attemptLogin();
			}
		}
		
////////////////////////////////////////////////////////////////////////////
		
		Intent intent = getIntent();
		String str_uid = null;
		if(intent.getExtras()!=null)
		{
			str_uid = intent.getExtras().get("uid").toString();			
			uIdEdit.setText(str_uid);
		}
//		if(uid!=null)
//		uIdEdit.setText(uid);
		
//		NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
//		notifyMessage(nm, "hihi", "i'msohigh");
	}
	private void notifyMessage(NotificationManager nm, String title, String msg)
	{
		Context context = getApplicationContext();
		Intent intent = new Intent(this,MainActivity.class);
		Notification noti = new Notification(R.drawable.kim,msg,System.currentTimeMillis());
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
		noti.setLatestEventInfo(this, title, msg, pendingIntent);
		noti.number =0;
		nm.notify(5555,noti);
	}
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	
		Intent intent = new Intent(MainActivity.this,
				FindAccountActivity.class);
		startActivity(intent);
	
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		uIdEdit.setError(null);
		uPwEdit.setError(null);

		// Store values at the time of the login attempt.
		uId = uIdEdit.getText().toString();
		uPassword = uPwEdit.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(uPassword)) {
			uPwEdit.setError(getString(R.string.error_field_required));
			focusView = uPwEdit;
			cancel = true;
		} else if (uPassword.length() < 4) {
			uPwEdit.setError(getString(R.string.error_invalid_password));
			focusView = uPwEdit;
			cancel = true;
		}

		// Check for a valid id.
		if (TextUtils.isEmpty(uId)) {
			uIdEdit.setError(getString(R.string.error_field_required));
			focusView = uIdEdit;
			cancel = true;
		}
		// else if (!uId.contains("@")) {
		// uIdEdit.setError(getString(R.string.error_invalid_id));
		// focusView = uIdEdit;
		// cancel = true;
		// }

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		Log.i("FLEXIBLE","s1");
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			Log.i("FLEXIBLE","s2");
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);
			Log.i("FLEXIBLE","s3");
			mLoginStatusView.setVisibility(View.VISIBLE);
			Log.i("FLEXIBLE","s4");
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});
			Log.i("FLEXIBLE","s5");
			mLoginFormView.setVisibility(View.VISIBLE);
			Log.i("FLEXIBLE","s6");
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
			Log.i("FLEXIBLE","s8");
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: 여기에서 백그라운드로 ID/PW 검색.
			// ///////////////////////////////////////////////////////////////////////////////////////////////////////
			
			String in_passwd = null;
			try {
				URL url = new URL(
						"http://192.168.0.205:8080/com.lg.project.myexample.cmd.RetrieveCmd.vcc?param=members_info,uid,"
								+ uIdEdit.getText().toString());

				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(url.openStream(), "utf-8");

				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT) {
					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:
						break;
					case XmlPullParser.START_TAG:
						if (parser.getName().equals("upw")) {
							in_passwd = parser.nextText();
							if (uPwEdit.getText().toString()
									.compareTo(in_passwd) == 0) {
								is_login = true;
							}

						}
						break;
					case XmlPullParser.END_TAG:
						break;
					}
					eventType = parser.next();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

			// TODO: 새로운 계정 등록.. 인텐트로 ID/PW를 넘겨주고,
			// RegistMemberActivity 에서 받아서 ID/PW 필드에 자동 입력
			Log.i("된다","djdkend");

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			Log.i("FLEXIBLE","1");
			mAuthTask = null;
			Log.i("FLEXIBLE","2");
			
			Log.i("FLEXIBLE","3");
			Cursor c = localDB.rawQuery("select * from LOGIN_INFO;", null);
			MUtils.loge("loginInfo.getcount() = " + c.getCount());
			if (is_login) {
				if(c.getCount() > 0 ){
					localDB.execSQL("update LOGIN_INFO "
							+ "set uId='" + uIdEdit.getText().toString() + "', "
							+ "uPw='"	+ uPwEdit.getText().toString() + "';");
				}else{
					localDB.execSQL("insert into LOGIN_INFO (uId, uPw) "
							+ "VALUES('" + uIdEdit.getText().toString() + "', '"
							+ uPwEdit.getText().toString() + "');");
				}

				SyncronizeContactsThread t = new SyncronizeContactsThread(getBaseContext());
				t.start();
				
				try {
					t.join();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Intent regIntent = new Intent(MainActivity.this,
						GroupListActivity.class);
				regIntent.putExtra("uid", uIdEdit.getText());
				startActivity(regIntent);
				finish();
			} else {
				showProgress(false);
				Log.i("FLEXIBLE","djdkend");
				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setTitle("ID입력오류!");
				builder.setMessage("ID또는 패스워드가 옳지 않습니다.");
				
				builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}
				});
				builder.show();
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}
		

	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == event.KEYCODE_BACK) {
			finish();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
}
